<?php
namespace app\api\controller;

use app\api\model\Order as OrderModel;
use think\Validate;
use app\api\model\User;
use app\api\model\UserAuth;
use app\api\model\OrderLog;
use app\api\model\OrderComment;
use app\api\model\Transaction;
use app\api\model\UserInfo;
use app\api\model\EvaluateDetail;

class Order extends Auth
{
    //index
    public function index()
    {
        return 'index';
    }

    //担保交易列表
    public function order_list()
    {

        $user_id = $this->user["user_id"];

        //显示自己的订单列表
        $order_list = OrderModel::alias('o')
            ->where(['buyer_id | seller_id'=>$user_id])
            ->join('jk_user_authentications b', 'b.user_id = o.buyer_id', 'LEFT')
            ->join('jk_user_authentications s', 's.user_id = o.seller_id', 'LEFT')
            ->field('o.*, b.true_name as buyer_truename, s.true_name as seller_truename')
            ->order('o.create_at DESC')
            ->paginate($this->number);

        $list = formatPage('order_list',$order_list);

        return success($list, '数据获取成功');
    }

    //预算接口
    public function order_budget()
    {
        //验证器
        $validate = new Validate([
            ['amount', 'require|float|egt:0', '价格最小为0'],
            ['type', 'require|between:1,4', '类型为1~4'],
        ]);
        if(!$validate->check(request()->param())) {
            return error($validate->getError());
        }

        //@param
        $amount = request()->param()['amount'];
        $type = request()->param()['type'];

        $price = price_budget($amount,$type);

        return success(['price'=>$price],'数据获取成功');
    }

    //担保交易添加
    public function order_add()
    {
        //验证器
        $validate = new Validate([
            ['username', 'require|number|length:11', '账户错误'],
            ['logic', 'require|between:1,2', '身份标识错误'],
            ['amount', 'require|float|egt:0', '价格最小为0'],
            ['agency_fee_type', 'require|between:1,4', '类型为1~4'],
            ['text', 'require', '交易信息不能为空'],
        ]);
        if(!$validate->check(request()->param())) {
            return error($validate->getError());
        }

        //@param
        $username = request()->param()['username'];
        $logic = request()->param()['logic'];
        $amount = request()->param()['amount'];
        $agency_fee_type = request()->param()['agency_fee_type'];
        $text = request()->param()['text'];

        $user_id = $this->user["user_id"];

        if($username == $user_id){
            return error('请重新输入对方账户');
        }

        $is_register = User::get(['username' => $username]);
        if ($is_register){
            $is_aut = UserAuth::get(['user_id' => $is_register->user_id]);
            if($is_aut->status != 1){
                return error('对方账号未认证');
            }
        }else{
            return error('对方账号不存在');
        }

        if($logic == 1){
            $data['buyer_id'] = $user_id;
            $data['seller_id'] = $is_register->user_id;
        }elseif ($_POST['logic'] == 2){
            $data['buyer_id'] = $is_register->user_id;
            $data['seller_id'] = $user_id;
        }
        $data['order_id'] = get_order_num();
        $data['price'] = $amount;
        $data['agency_fee_type'] = $agency_fee_type;
        $data['text'] = $text;
        $data['create_at'] = time();
        $data['recipient_id'] = $is_register->user_id;

        $orders = new OrderModel($data);
        $orders->save();
        if($orders->id){
            //写日志1
            if ($user_id == $orders->buyer_id){
                $operator_id = 1;
            }elseif($user_id == $orders->seller_id){
                $operator_id = 2;
            }else{
                return error('网络繁忙，请重新提交');
            }

            $log_data = array(
                'operator_id' => $operator_id,
                'order_id' => $orders->order_id,
                'user_id' => $user_id,
                'create_at' => time(),
                'content' => '发起交易，等待对方接受交易',
            );
            $order_logs = new OrderLog;
            $order_logs->save($log_data);

            return success(['order'=>$orders->order_id], '提交成功');
        }else{
            return error('提交失败');
        }
    }

    //订单查询 订单id
    public function order_info()
    {
        //验证器
        $validate = new Validate([
            ['order_id', 'require|number', '订单号错误'],
            ['order_comment_id', 'number', '错误的参数'],
        ]);
        if(!$validate->check(request()->param())) {
            return error($validate->getError());
        }

        //@param
        $order_id = request()->param()['order_id'];

        //是否点击评论消息进入详情
        if(isset(request()->param()['order_comment_id'])){
            $order_comment_id = request()->param()['order_comment_id'];

            $is_new = new OrderComment;
            $is_new->save(['is_new'=>0],['id'=>$order_comment_id]);
        }

        $user_id = $this->user['user_id'];

        //订单
        $orders_obj = OrderModel::alias('o')
            ->where(['order_id'=>$order_id])
            ->join('jk_user_informations b', 'b.user_id = o.buyer_id', 'LEFT')
            ->join('jk_user_informations s', 's.user_id = o.seller_id', 'LEFT')
            ->field('o.*, b.nickname as buyer_nickname, s.nickname as seller_nickname')
            ->find();

        if($user_id != $orders_obj->buyer_id && $user_id != $orders_obj->seller_id){
            return error('错误的访问');
        }

        //价格 买家需付、卖家所得
        $price = price_budget($orders_obj->price,$orders_obj->agency_fee_type);

        //评论
        $order_comments = new OrderComment;
        $comments_obj = $order_comments->where(['order_id' => $order_id])->order('create_at asc')->select();

        //日志
        $logs_obj = OrderLog::alias('o')
            ->where(['order_id'=>$order_id])
            ->join('jk_user_informations u', 'u.user_id = o.user_id', 'LEFT')
            ->field('o.*, u.nickname as user_nickname')
            ->order('create_at asc')
            ->select();

        //买家认证信息
        $buyer_info = UserAuth::alias('a')
            ->where(['a.user_id' => $orders_obj->buyer_id])
            ->join('jk_users u', 'u.user_id = a.user_id', 'LEFT')
            ->join('jk_user_informations i', 'i.user_id = a.user_id', 'LEFT')
            ->field('a.user_id, a.true_name, a.phone, u.username, i.qq, i.user_icon_url, i.nickname')
            ->find();
        //卖家认证信息
        $seller_info = UserAuth::alias('a')
            ->where(['a.user_id' => $orders_obj->seller_id])
            ->join('jk_users u', 'u.user_id = a.user_id', 'LEFT')
            ->join('jk_user_informations i', 'i.user_id = a.user_id', 'LEFT')
            ->field('a.user_id, a.true_name, a.phone, u.username, i.qq, i.user_icon_url, i.nickname')
            ->find();

        return success([
            'orders_obj' => $orders_obj,
            'comments_obj' => $comments_obj,
            'logs_obj' => $logs_obj,
            'price' => $price,
            'buyer_info' => $buyer_info,
            'seller_info' => $seller_info,
        ],'数据获取成功');
    }

    //评论 订单号，评论内容
    public function order_comment()
    {
        //验证器
        $validate = new Validate([
            ['order_id', 'require|number', '订单号错误'],
            ['text', 'require', '评论不能为空'],
        ]);
        if(!$validate->check(request()->param())) {
            return error($validate->getError());
        }

        //@param
        $order_id = request()->param()['order_id'];
        $text = request()->param()['text'];

        $user_id = $this->user['user_id'];

        $order_comments = new OrderComment;
        $order_comments->data([
            'user_id' => $user_id,
            'order_id' => $order_id,
            'create_at' => time(),
            'text' => $text,
        ]);
        $comments_obj = $order_comments->save();
        if($comments_obj){
            return success('','评论成功');
        }else{
            return error('评论失败');
        }
    }

    //对方确认
    public function order_confirm()
    {
        //验证器
        $validate = new Validate([
            ['order_id', 'require|number', '订单号错误'],
            ['type', 'require|between:0,1', '错误的选择'],
        ]);
        if(!$validate->check(request()->param())) {
            return error($validate->getError());
        }

        //@param
        $order_id = request()->param()['order_id'];
        $type = request()->param()['type'];

        $user_id = $this->user['user_id'];

        $orders = new OrderModel;
        $orders_obj = $orders->where(['order_id'=>$order_id,'recipient_id'=>$user_id,'status'=>1])->find();
        if(is_object($orders_obj)){
            //接受和拒绝
            if($type == 1){
                $orders_up = $orders->save(['status'=>2],['id'=>$orders_obj->id]);
                if($orders_up){
                    //日志
                    if ($user_id == $orders_obj->buyer_id){
                        $operator_id = 1;
                    }elseif($user_id == $orders_obj->seller_id){
                        $operator_id = 2;
                    }

                    $log_data = array(
                        'operator_id' => $operator_id,
                        'order_id' => $orders_obj->order_id,
                        'user_id' => $user_id,
                        'create_at' => time(),
                        'content' => '接受了交易，下一步等待对方付款',
                    );
                    $order_logs = new OrderLog;
                    $order_logs->save($log_data);

                    return success('','成功接受交易');
                }else{
                    return error('网络繁忙，请重新提交');
                }
            }elseif($type == 0){
                $tra = new Transaction;
                //开启事务处理
                $tra->startTrans();
                $orders->startTrans();

                $orders_up = $orders->save(['status'=>9],['id'=>$orders_obj->id]);
                //处理无效订单利润
                $tra->data([
                    'order_id' => $orders_obj->order_id,
                    'user_id' => $orders_obj->buyer_id,
                    'price' => $orders_obj->price,
                    'profit' => 0,
                    'create_at' => time(),
                    'type' => 2,
                ]);
                $tra_obj = $tra->save();
                if($orders_up && $tra_obj){
                    //提交事务
                    $orders->commit();
                    $tra->commit();

                    //日志
                    if ($user_id == $orders_obj->buyer_id){
                        $operator_id = 1;
                    }elseif($user_id == $orders_obj->seller_id){
                        $operator_id = 2;
                    }

                    $log_data = array(
                        'operator_id' => $operator_id,
                        'order_id' => $orders_obj->order_id,
                        'user_id' => $user_id,
                        'create_at' => time(),
                        'content' => '拒绝了交易，订单结束',
                    );
                    $order_logs = new OrderLog;
                    $order_logs->save($log_data);

                    return success('','成功拒绝交易');
                }else{
                    //事务回滚
                    $orders->rollback();
                    $tra->rollback();

                    return error('网络繁忙，请重新提交');
                }
            }
        }else{
            return error('错误操作');
        }
    }

    //买家确认收货
    public function order_collect_goods()
    {
        //验证器
        $validate = new Validate([
            ['order_id', 'require|number', '订单号错误'],
        ]);
        if(!$validate->check(request()->param())) {
            return error($validate->getError());
        }

        //@param
        $order_id = request()->param()['order_id'];

        $user_id = $this->user['user_id'];

        $orders = new OrderModel;
        $orders_obj = $orders->where(['order_id'=>$order_id,'buyer_id'=>$user_id,'status'=>3])->find();
        if(is_object($orders_obj)){
            $orders_up = $orders->save(['status'=>4,'is_settlement'=>2,'end_time'=>time()],['id'=>$orders_obj->id]);
            if($orders_up){
                //日志
                $log_data = array(
                    'operator_id' => 1,
                    'order_id' => $orders_obj->order_id,
                    'user_id' => $user_id,
                    'create_at' => time(),
                    'content' => '已确认收到货，完成交易',
                );
                $order_logs = new OrderLog;
                $order_logs->save($log_data);

                return success(['order_id'=>$order_id],'成功确认收货');
            }else{
                return error('网络繁忙');
            }
        }else{
            return error('错误的操作');
        }
    }

    //订单评价
    public function order_evaluate()
    {
        $validate = new Validate([
            ['order_id', 'require|number', '订单号错误'],
            ['evaluate', 'require|number|between:1,3', '请选择评价等级'],
            ['content', 'require', '请输入评价内容'],
        ]);
        if(!$validate->check($this->request->param())) {
            return error($validate->getError());
        }

        //@prarm
        $order_id = request()->param()['order_id'];
        $evaluate = request()->param()['evaluate'];
        $content = request()->param()['content'];

        $user_id = $this->user['user_id'];

        $orders = new OrderModel;
        $orders_obj = $orders->where([
            'order_id' => $order_id,

            'status' => 4,
            'is_evaluate' => 0,
        ])->find();
        if (is_object($orders_obj)) {
            $inf = new UserInfo;
            $inf_obj = $inf->where(['user_id' => $orders_obj->seller_id])->find();
            if (is_object($inf_obj)) {
                $eva = new EvaluateDetail;
                //开启事务 更新订单表、用户信息详情表
                $orders->startTrans();
                $inf->startTrans();
                $eva->startTrans();

                //好、中、差
                if($_POST['evaluate'] == 1){
                    $praise = $inf_obj->praise + 1;
                    $inf_up = $inf->save(['praise'=>$praise],['id'=>$inf_obj->id]);
                }elseif($_POST['evaluate'] == 2){
                    $commonly = $inf_obj->commonly + 1;
                    $inf_up = $inf->save(['commonly'=>$commonly],['id'=>$inf_obj->id]);
                }elseif($_POST['evaluate'] == 3){
                    $negative_comment = $inf_obj->negative_comment + 1;
                    $inf_up = $inf->save(['negative_comment'=>$negative_comment],['id'=>$inf_obj->id]);
                }

                //订单已评价
                $orders_up = $orders->save(['is_evaluate'=>1],['id'=>$orders_obj->id]);

                //添加评价详情
                $eva_data = array(
                    'order_id' => $order_id,
                    'user_id' => $user_id,
                    'create_at' => time(),
                    'content' => $content,
                    'evaluate' => $evaluate,
                );
                $eva_obj = $eva->save($eva_data);

                if($inf_up && $orders_up && $eva_obj){
                    //提交事务
                    $orders->commit();
                    $inf->commit();
                    $eva->commit();

                    return success('','评价成功');
                }else{
                    //事务回滚
                    $orders->rollback();
                    $inf->rollback();
                    $eva->rollback();

                    return error('评价失败');
                }
            }else{
                return error('被评人不存在');
            }
        }else{
            return error('错误的操作');
        }
    }
}